package guava;

import com.google.common.base.Ticker;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheBuilderSpec;
import com.google.common.cache.CacheLoader;
import org.junit.Test;

/**
 * CacheBuilderSpec：构造CacheBuilder实例
 * User: Realfighter
 * Date: 2014/12/6
 * Time: 8:40
 */
public class CacheBuilderSpecTest {

    @Test
    public void testFirst() {
        //配置CacheBuilder的字符串
        String configString = "concurrencyLevel=10,refreshAfterWrite=5s";
        //解析字符串，创建CacheBuilderSpec实例
        CacheBuilderSpec spec = CacheBuilderSpec.parse(configString);
        //通过CacheBuilderSpec实例构造CacheBuilder实例
        CacheBuilder.from(spec);
    }

    @Test
    public void testCacheBuilderSpec() {
        //配置CacheBuilder的字符串
        String spec = "concurrencyLevel=10,expireAfterAccess=5m,softValues";
        //解析字符串，创建CacheBuilderSpec实例
        CacheBuilderSpec cacheBuilderSpec = CacheBuilderSpec.parse(spec);
        //通过CacheBuilderSpec实例构造CacheBuilder实例
        CacheBuilder cacheBuilder = CacheBuilder.from(cacheBuilderSpec);
        //ticker：设置缓存条目过期时间
        //removalListener：监听缓存条目的移除
        cacheBuilder.ticker(Ticker.systemTicker())
                //to fix the compile bug for testing
//                .removalListener(new TradeAccountRemovalListener())
                .build(new CacheLoader<String, TradeAccount>() {
                    @Override
                    public TradeAccount load(String key) throws
                            Exception {
                        return null;//to fix the compile bug for testing
//                        return
//                                tradeAccountService.getTradeAccountById(key);
                    }
                });

    }

    public class TradeAccount {
        private String id; //ID
        private String owner; //所有者
        private double balance; //余额
    }

}
